package com.ler.pai.controller;

import com.alibaba.fastjson.JSONObject;
import com.ler.pai.util.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lww
 * @date 2020-01-30 18:54
 */
@Api(value = "/short", description = "短链生成")
@RestController
@RequestMapping("/short")
@Slf4j
public class ShortUrlController {

	private static final String SHORT_URL = "https://www.98api.cn/api/sinaDwz.php?url=";

	@ApiOperation("短链生成")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "url", value = "需要转为短链的url", required = true),
	})
	@PostMapping("/url")
	public String getUrl(String url) {
		log.info("ShortUrlController_getUrl_url:{}", url);
		Assert.isTrue(StringUtils.isNotBlank(url), "参数错误，链接为空！");
		String s = HttpUtils.sendGetHttps(SHORT_URL + url, null, null);
		Assert.isTrue(s != null, "生成短链失败！");
		JSONObject jsonObject = JSONObject.parseObject(s);
		String shortUrl = jsonObject.getString("short_url");
		log.info("ShortUrlController_getUrl_shortUrl:{}", shortUrl);
		return shortUrl;
	}

}
